package com.sanxia.market.service.index;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sanxia.common.utils.HttpClientUtil;
import com.sanxia.common.utils.JsonUtil;
import com.sanxia.common.utils.StringUtil;
import com.sanxia.market.entity.HbAction;
import com.sanxia.market.entity.User;
import com.sanxia.market.entity.WxInfo;
import com.sanxia.market.service.HbActionService;
import com.sanxia.market.service.UserService;
import com.sanxia.market.service.WxInfoService;
import com.sanxia.market.service.hongbao.HongbaoService;




 /**
* @Title: HongbaoLogService.java
* @Package com.sanxia.market.service
* @Description:
* @author 赵贯男
* @date 2019-01-18 13:33:52
* @version V1.0
* create by codeFactory
*/
@Service("IndexService")
public class IndexService {

	 @Autowired
	 private WxInfoService wxInfoService;

	 @Autowired
	 private UserService userService;
	 @Autowired
	 HongbaoService hongbaoService;

	 @Autowired
	 private HbActionService hbActionService;


	 public String SQ(String mchid, String action) {
		 Map<String, Object> paramMap = new HashMap<String, Object>();
		 paramMap.put("mchId", mchid);
		 WxInfo wxInfo = wxInfoService.getBy(paramMap);

		 String wx_appid = wxInfo.getWxAppid();
		 String mch_name = wxInfo.getMchName();
		 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
		 String redirect_uri = "http://share.shijiebox.com/hongbao/index/redirect_uri";
		 //appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
		 url = url + "appid=" + wx_appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=" + action + "," + mchid + "#wechat_redirect";
		 return url;
	 }

	 public String redirect_uri(String code, String state) {
		 String[] sta = state.split(",");
		 String action = sta[0];
		 String mchid = sta[1];
		 Map<String, Object> paramMap = new HashMap<String, Object>();
		 paramMap.put("mchId", mchid);
		 WxInfo wxInfo = wxInfoService.getBy(paramMap);
		 String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxInfo.getWxAppid() + "&secret=" + wxInfo.getWxAppSecret() + "&code=" + code + "&grant_type=authorization_code";
		 String rest = HttpClientUtil.doGet(url);
		 Map map = (Map) JsonUtil.jsonStr2Bean(rest, Map.class);
		 String openid = (String) map.get("openid");
		 String access_token = (String) map.get("access_token");
		 String userinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
		 String restUserinfo = HttpClientUtil.doGet(userinfoUrl);
		 Map mapUserinfo = (Map) JsonUtil.jsonStr2Bean(restUserinfo, Map.class);
//{"openid":"oKvRh5oB_kWkH1NrgfXnszBisrLM","nickname":"醉卧雕龙肪","sex":1,"language":"zh_CN","city":"","province":"","country":"中非共和国","headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Q0j4TwGTfTKlJFUaaSJhc47BxdvRST4dUuCJkvv5fDp6xG0LsicNO5yypIp5rQRalAQSKtwuIQldLYUQoTe2rfg\/132","privilege":[]}
		 //filterEmoji(mapUserinfo.getNickname())
		 paramMap.clear();
		 paramMap.put("action", action);
		 HbAction hbAction = hbActionService.getBy(paramMap);
		 paramMap.clear();
		 paramMap.put("userOpenid", openid);
		 paramMap.put("mechId", mchid);
		 User user = userService.getBy(paramMap);
		 if (StringUtil.isEmpty(user)) {
			 user = new User();
			 user.setMechId(mchid);
			 user.setUserOpenid(openid);
			 user.setUserType("0");
			 user.setAddTime(new Date());
			 user.setUserNickName(mapUserinfo.get("nickname")+"");
			 user.setUserPhoto(mapUserinfo.get("headimgurl")+"");
			 userService.insertOne(user);
		 }else {
			 user.setUserNickName(mapUserinfo.get("nickname")+"");
			 user.setUserPhoto(mapUserinfo.get("headimgurl")+"");
			 userService.updateOne(user);
		 }

		 return hbAction.getUrl() + "?mchid=" + mchid + "&openid=" + openid;
	 }
	 
	 public String SQ2(String mchid, String action,String openid) {
		 System.out.println("开始拼sq2l ");
		 Map<String, Object> paramMap = new HashMap<String, Object>();
		 paramMap.put("mchId", mchid);
		 WxInfo wxInfo = wxInfoService.getBy(paramMap);

		 String wx_appid = wxInfo.getWxAppid();
		 String mch_name = wxInfo.getMchName();
		 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
		 String redirect_uri = "http://share.shijiebox.com/hongbao/index/redirect_uri2";
		 //appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
		 url = url + "appid=" + wx_appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=" + action + "," + openid + "#wechat_redirect";
		 System.out.println("自己请求json地址");
		 this.sendGet(url);
		 System.out.println("自己请求json地址结束");
		 return url;
	 }

	 public String redirect_uri2(String code, String state) {
		 String[] sta = state.split(",");
		 String action = sta[0];
		 String openid = sta[1];
		 Map<String, Object> paramMap = new HashMap<String, Object>();
		 paramMap.put("mchId", "2");
		 WxInfo wxInfo = wxInfoService.getBy(paramMap);
		 String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxInfo.getWxAppid() + "&secret=" + wxInfo.getWxAppSecret() + "&code=" + code + "&grant_type=authorization_code";
		 String rest = HttpClientUtil.doGet(url);
		 Map map = (Map) JsonUtil.jsonStr2Bean(rest, Map.class);
		 String now_openid = (String) map.get("openid");
		 
		 System.out.println("父级id:"+openid+";自己的："+now_openid);
		 System.out.println("父级id:"+openid+";自己的："+now_openid);
		 System.out.println("父级id:"+openid+";自己的："+now_openid);
		 System.out.println("父级id:"+openid+";自己的："+now_openid);
		 System.out.println("父级id:"+openid+";自己的："+now_openid);
		 
		 hongbaoService.initUserInfo(now_openid, openid);		 
		 
		 return "";
	 }
	 
	  
	 
	 

	 public static String filterEmoji(String source) {
		 if (source == null) {
			 return source;
		 }
		 Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
				 Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		 Matcher emojiMatcher = emoji.matcher(source);
		 if (emojiMatcher.find()) {
			 source = emojiMatcher.replaceAll("*");
			 return source;
		 }
		 return source;


	 }

	 public static String sendGet(String url) {
			String result = "";
			BufferedReader in = null;
			try {
				URL realUrl = new URL(url);
				// 打开和URL之间的连接
				URLConnection connection = realUrl.openConnection();
				// 设置通用的请求属性
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("user-agent",
						"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				// 建立实际的连接
				connection.connect();
				// 定义 BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(
						connection.getInputStream(), "utf-8"));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
			} catch (Exception e) {
				System.out.println("发送GET请求出现异常！" + e);
				e.printStackTrace();
			}
			// 使用finally块来关闭输入流
			finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return result;
		} 
	 
	 
 }
